#include <stdio.h>
#include <ctype.h>
#include <string.h>

#define KEY 6
char *keyword[KEY] = {"for", "if", "then", "else", "while", "do"};
char id[1024];
int num;
int token;

void lexical(FILE *fp) {
    char x = getc(fp);
	char temp;
	FILE *f;
	int i;
	char *array=new char[20];
	f=fp;

	num = 0;
	strcpy(id, "\0");
	if(x>='a' && x<='z')
	{
	    array[i]=x;
		for(i=0;i<5;i++)
		{
		temp=getc(f++);
		array[i]=temp;
		 if(array=="for")
		 {token=1;strcpy(id, keyword[0]);}
		 else if(array=="if")
		 {token=2;strcpy(id, keyword[1]);}
		 else if(array=="then")
		 {token=3;strcpy(id, keyword[2]);}
		 else if(array=="else")
		 {token=4;strcpy(id, keyword[3]);}
		 else if(array=="while")
		 {token=5;strcpy(id, keyword[4]);}
		 else if(array=="do")
		 {token=6;strcpy(id, keyword[5]);}
		 else {token=10;strcpy(id, x);}
	   }
	}
	else if(x>='0' && x<='9')  {token=11;num=x-48;}
	else if(x=="+")  {token=13;strcpy(id, x);}
	else if(x=="-")  {token=14;strcpy(id, x);}
	else if(x=="*")  {token=15;strcpy(id, x);}
	else if(x=="/")  {token=16;strcpy(id, x);}
	else if(x==":")  {token=17;strcpy(id, x);}
	else if(x==":=")  {token=18;strcpy(id, x);}
	else if(x=="<")  {token=20;strcpy(id, x);}
	else if(x=="<>")  {token=21;strcpy(id, x);}
	else if(x=="<=")  {token=22;strcpy(id, x);}
	else if(x==">")  {token=23;strcpy(id, x);}
	else if(x==">=")  {token=24;strcpy(id, x);}
	else if(x=="=")  {token=25;strcpy(id, x);}
	else if(x==";")  {token=26;strcpy(id, x);}
	else if(x=="(")  {token=27;strcpy(id, x);}
	else if(x==")")  {token=28;strcpy(id, x);}
	else if(x=="#")  {token=0;strcpy(id, x);}
	fp=fp++;

	//process x
	//process each regex here
	//store the result in global variables id, num, or token
	//in case of backtrack, use
	//ungetc(x, fp);

}

int main(int argc, const char *argv[])
{
	if(argc < 2) {
		printf("insufficient args\n");
		return 1;
	}
	FILE *fp = fopen(argv[1], "r");
	do {
		lexical(fp);
		switch(token) {
			case 10: printf("(id, %s)\n", id); break;
			case 11: printf("(num, %d)\n", num); break;
			case -1: printf("error!\n"); break;
			default: printf("(%d, %s)\n", token, id);
		}
	} while(token != 0);


	fclose(fp);
	return 0;
}
